package blueeye.os
{
	public class os
	{
		
		import mx.rpc.AsyncRequest; 
      	import mx.controls.Alert;
      	import mx.collections.ArrayCollection;
      	import mx.events.ListEvent;

      	import org.opensocial.client.base.*;
      	import org.opensocial.client.core.*;
      	import org.opensocial.client.features.*;
      	import org.opensocial.client.jswrapper.*;
      	import org.opensocial.client.util.*;
	
	    private var client:JsWrapperClient;
	    private var helper:SyncHelper;
	
      	private static var logger:Logger = new Logger();
   		

      	[Bindable]
      	public var people:ArrayCollection = new ArrayCollection();
		
		public function os()
		{
			// Create the output box for information displaying
        	var printer:TextFieldPrinter = new TextFieldPrinter(2, 160, 450, 330);
        	//this.rawChildren.addChild(printer);
        //var printer:FirebugPrinter = new FirebugPrinter();
        	Logger.initialize(printer, 1);
        	logger.info("OpenSocial(0.8) AS3 Client Library in Flex 3");
        	logger.log(new Date());

        // Initialize Client and start
        	client = new JsWrapperClient();
        	client.addEventListener(OpenSocialClientEvent.CLIENT_READY, onReady);
        	client.start();

        	helper = new SyncHelper(client);
		}

      public function onReady(event:OpenSocialClientEvent):void {
        logger.info("Domain: " + helper.getDomain());
        logger.info("ContainerDomain: " + helper.getContainerDomain());
        logger.info("CurrentView: " + helper.getCurrentView());
        logger.info("Client Ready.");
      }


      // -------------------------------------------------------------
      //  Demo Actions
      // -------------------------------------------------------------

      // ----------------- Fetch Me ------------------
      public function fetchMe():void {
      	
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.PEOPLE_GET,
            new PeopleRequestOptions()
                .setUserId("@me")
                .setGroupId("@self"));
        req.addEventListener(ResponseItemEvent.COMPLETE, fetchMeEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, fetchMeEventErrorHandler);
        req.send(client);
        people.removeAll();
      }

      public function fetchMeEventHandler(event:ResponseItemEvent):void {
      	var p:Person = event.response.getData();
        logger.info(p.getDisplayName());
        people.addItem(p);
      }

      public function fetchMeEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("fetch me failed: " + event.response.getErrorMessage());
      }


      // ----------------- Fetch Friends ------------------
      public function fetchFriends():void {
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.PEOPLE_GET,
            new PeopleRequestOptions()
                .setUserId("@me")
                .setGroupId("@friends")
                .setCount(2)
                .setStartIndex(0));
        req.addEventListener(ResponseItemEvent.COMPLETE, fetchFriendsEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, fetchFriendsEventErrorHandler);
        req.send(client);
        people.removeAll();
      }

      public function fetchFriendsEventHandler(event:ResponseItemEvent):void {
        var c:Collection = event.response.getData();
        logger.info(c.toDebugString());
        var arr:Array = c.getArray();
        for (var i:int = 0; i < arr.length; i++) {
          var p:Person = arr[i];
          logger.info(p.getDisplayName());
          people.addItem(p);
        }

        if (c.getRemainingSize() > 0) {
          var req:AsyncDataRequest = event.target as AsyncDataRequest;
          (req.getOptions() as PeopleRequestOptions).setStartIndex(c.getNextOffset());
          req.send(client);
        }
      }

      public function fetchFriendsEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("fetch friends failed: " + event.response.getErrorMessage());
      }

      // ----------------- Send Message ------------------
      public function sendMessage():void {
        // the change for myspace. myspace is not support Message object's type equal to null.
        var message:Message = Message.newInstance("Hello World...", "My new message.", Message.Type.EMAIL);
        logger.log(message.toRawObject());

        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.REQUEST_SEND_MESSAGE,
            new UIRequestOptions()
                .setRecipientIds(["@viewer"])
                .setMessage(message));
        req.addEventListener(ResponseItemEvent.COMPLETE, sendMessageEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, sendMessageEventErrorHandler);
        req.send(client);
      }

      public function sendMessageEventHandler(event:ResponseItemEvent):void {
        logger.info("msg sent.");
      }
      public function sendMessageEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("msg sending failed: " + event.response.getErrorMessage()
            + " msg error code:" + event.response.getErrorCode());
      }


      // ----------------- Create Activity ------------------
      public function createActivity():void {
        var activity:Activity = Activity.newInstance("My new activity!", "Hello World...");

        logger.log(activity.toRawObject());
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.REQUEST_CREATE_ACTIVITY,
            new UIRequestOptions()
                .setActivity(activity));
        req.addEventListener(ResponseItemEvent.COMPLETE, createActivityEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, createActivityEventErrorHandler);
        req.send(client);
      }

      public function createActivityEventHandler(event:ResponseItemEvent):void {
        logger.info("activity created");
      }
      public function createActivityEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("activity creation failed: " + event.response.getErrorMessage());
      }

      // ----------------- Fetch Activities ------------------
      public function fetchActivities():void {
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.ACTIVITIES_GET,
            new ActivitiesRequestOptions());
        req.addEventListener(ResponseItemEvent.COMPLETE, fetchActivitiesEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, fetchActivitiesEventErrorHandler);
        req.send(client);
      }

      public function fetchActivitiesEventHandler(event:ResponseItemEvent):void {
        var c:Collection = event.response.getData();
        logger.info(c.toDebugString());
        var arr:Array = c.getArray();
        for (var i:int = 0; i < arr.length; i++) {
          var a:Activity = arr[i];
          logger.info(a.toString());
        }

        if (c.getRemainingSize() > 0) {
          var req:AsyncDataRequest = event.target as AsyncDataRequest;
          (req.getOptions() as ActivitiesRequestOptions).setStartIndex(c.getNextOffset());
          req.send(client);
        }
      }

      public function fetchActivitiesEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("fetch activities failed: " + event.response.getErrorMessage());
      }

      // ----------------- Make Request ------------------
      public function makeRequest():void {
        var req:ProxiedRequest = new ProxiedRequest(
            "http://www.google.com/crossdomain.xml",
            new ProxiedRequestOptions()
                .setContentType(GadgetsIo.ContentType.TEXT));
        req.addEventListener(ProxiedRequestEvent.COMPLETE, makeRequestEventHandler);
        req.addEventListener(ProxiedRequestEvent.ERROR, makeRequestEventErrorHandler);
        req.send(client);
      }

      public function makeRequestEventHandler(event:ProxiedRequestEvent):void {
        logger.info(event.response.getData());
      }

      public function makeRequestEventErrorHandler(event:ProxiedRequestEvent):void {
        logger.info("make request failed: " + event.response.getRC()
                    + "|" + event.response.getText());
      }


      // ----------------- Call RPC ------------------
      public function callRpc():void {
        // To use this, you need to first register the rpc service with name "srv-parent" on
        // container side. If you are using firefox+firebug and looking on a shindig container,
        // before clicking the "Call Rpc" button in the flash to call this method, copy+paste the
        // following codes to the console window:
        //
        // <code>
        // gadgets.rpc.register("srv-parent",function(){console.log(arguments);return "'srv-parent' returned."});
        // </code>
        var req:RPCRequest = new RPCRequest(null, "srv-parent", "abc", 123, {'xyz':456});
        req.addEventListener(RPCRequestEvent.RPC_CALLBACK, callRpcEventHandler);
        req.send(client);
      }

      public function callRpcEventHandler(event:RPCRequestEvent):void {
        logger.info("--- invoked by the returning of 'srv-parent' ---");
        logger.log(event.returnValue);
      }


      // ----------------- Register RPC Service ------------------
      public function registerService():void {
        // To use this, you need to make a rpc call to "srv-app" from container side. If you are
        // using firefox+firebug and shindig container, click the "Register Srv" button in the
        // flash to call this method, then copy+paste the following codes to the console window
        // to test the rpc.
        // ("remote_iframe_0" assumes this flash app is the first app on the page)
        //
        // <code>
        // gadgets.rpc.call("remote_iframe_0","srv-app",function(r){console.log(r);},"abc", 123, {'xyz':456});
        // </code>
        var srv:RPCService = new RPCService("srv-app");
        srv.register(client);
        srv.addEventListener(RPCServiceEvent.RPC_SERVICE, serviceEventHandler);
      }

      public function serviceEventHandler(event:RPCServiceEvent):void {
        logger.info("--- invoked by 'srv-app' get called ---");
        logger.log(event.params);
        event.callback("'srv-app' returned.");
      }

      // ----------------- Share App ------------------
      /*public function shareApp(event:ListEvent):void {
        // To use this, you need First run "Fetch Friends" or "Fetch Me" and then click People.
        var p:Person = people.getItemAt(titleList.selectedIndex) as Person;
        var message:Message = Message.newInstance("Hey [recipient]! [sender] wants you to add [app]. It's way awesome!", "A fun way to view your profile!");
        logger.log(message.toRawObject());

        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.REQUEST_SHARE_APP,
            new UIRequestOptions()
                .setRecipientIds([p.getId()])
                .setReason(message));
        req.addEventListener(ResponseItemEvent.COMPLETE, shareAppEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, shareAppEventErrorHandler);
        req.send(client);
      }*/

      public function shareAppEventHandler(event:ResponseItemEvent):void {
        logger.info("msg sent.");
      }
      public function shareAppEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("msg sending failed: " + event.response.getErrorMessage());
      }

      // ----------------- Batch Request------------------
      public function batchRequest():void {
        var batch:BatchRequest = new BatchRequest();
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.PEOPLE_GET,
            new PeopleRequestOptions()
                .setUserId("@me")
                .setGroupId("@self"));

//        req.addEventListener(ResponseItemEvent.COMPLETE, batchFetchMeEventHandler);
//        req.addEventListener(ResponseItemEvent.ERROR, batchFetchMeEventErrorHandler);


        batch.add(req, "meProfile");

        req = new AsyncDataRequest(
            Feature.PEOPLE_GET,
            new PeopleRequestOptions()
                .setUserId("@me")
                .setGroupId("@friends")
                .setCount(2)
                .setStartIndex(0));
//
//        req.addEventListener(ResponseItemEvent.COMPLETE, batchFetchFriendsEventHandler);
//        req.addEventListener(ResponseItemEvent.ERROR, batchFetchFriendsEventErrorHandler);
//
        batch.add(req, "friendList");

        batch.addEventListener(ResponseItemEvent.COMPLETE, batchDataRequestEventHandler);
        batch.addEventListener(ResponseItemEvent.ERROR, batchDataRequestErrorHandler);
        batch.send(client);
      }

      public function batchDataRequestEventHandler(event:ResponseItemEvent):void {
        logger.info("===============  Batch Success   ================");
        var p:Person = event.response.getData("meProfile");
        logger.info("meProfile ===============  " + p.getDisplayName());

        var c:Collection = event.response.getData("friendList");
        var arr:Array = c.getArray();
        for (var i:int = 0; i < arr.length; i++) {
          var person:Person = arr[i];
          logger.info("friendList ===============  " + person.getDisplayName());
        }
        logger.info("===============  Batch Success   ================");
      }

      public function batchDataRequestErrorHandler(event:ResponseItemEvent):void {
        logger.info("===============  Batch Error   ================");
        logger.info(event.response.getErrorMessage());
        logger.info("===============  Batch Error   ================");
      }

      public function batchFetchMeEventHandler(event:ResponseItemEvent):void {
        var p:Person = event.response.getData();
        logger.info(p.getDisplayName());
        people.addItem(p);
      }

      public function batchFetchMeEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("fetch me failed: " + event.response.getErrorMessage());
      }

      public function batchFetchFriendsEventHandler(event:ResponseItemEvent):void {
        var c:Collection = event.response.getData();
        logger.info(c.toDebugString());
        var arr:Array = c.getArray();
        for (var i:int = 0; i < arr.length; i++) {
          var p:Person = arr[i];
          logger.info(p.getDisplayName());
          people.addItem(p);
        }

        if (c.getRemainingSize() > 0) {
          var req:AsyncDataRequest = event.target as AsyncDataRequest;
          (req.getOptions() as PeopleRequestOptions).setStartIndex(c.getNextOffset());
          req.send(client);
        }
      }

      public function batchFetchFriendsEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("fetch friends failed: " + event.response.getErrorMessage());
      }

      // ----------------- Update Appdata ------------------
      public function updateAppdata():void {
        var value:String = "random value: #12345";

        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.APP_DATA_UPDATE,
            new AppDataRequestOptions()
                .setDatum("randomKey", value));
        req.addEventListener(ResponseItemEvent.COMPLETE, updateAppdataEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, updateAppdataEventErrorHandler);
        req.send(client);
      }

      public function updateAppdataEventHandler(event:ResponseItemEvent):void {
        logger.info("update success!");
      }
      public function updateAppdataEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("update failed: " + event.response.getErrorMessage());
      }

      // ----------------- Get Appdata ------------------
      public function getAppdata():void {
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.APP_DATA_GET,
            new AppDataRequestOptions()
                .setKeys(["player"]));
        req.addEventListener(ResponseItemEvent.COMPLETE, getAppdataEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, getAppdataEventErrorHandler);
        req.send(client);
      }

      public function getAppdataEventHandler(event:ResponseItemEvent):void {
        var data:Object = event.response.getData();
        for (var key:String in data) {
          logger.info("UserID:" + key);
          logger.info("Value: " + data[key].randomKey);
        }
        logger.info("get success!");
      }
      public function getAppdataEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("get failed: " + event.response.getErrorMessage());
      }


      // ----------------- Delete Appdata ------------------
      public function deleteAppdata():void {
        var req:AsyncDataRequest = new AsyncDataRequest(
            Feature.APP_DATA_DELETE,
            new AppDataRequestOptions()
                .setKeys(["player"]));
        req.addEventListener(ResponseItemEvent.COMPLETE, deleteAppdataEventHandler);
        req.addEventListener(ResponseItemEvent.ERROR, deleteAppdataEventErrorHandler);
        req.send(client);
      }

      public function deleteAppdataEventHandler(event:ResponseItemEvent):void {
        logger.info("delete success!");
      }
      public function deleteAppdataEventErrorHandler(event:ResponseItemEvent):void {
        logger.info("delete failed: " + event.response.getErrorMessage());
      }
      
	}
}